//
//  LSEmotionKeyboardController.swift
//  EmotionKeyboard
//
//  Created by lj on 15/9/12.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

let LSEmotionViewCellID = "LSEmotionViewCellID"

class LSEmotionKeyboardController: UIViewController {
    
    /// 选中表情包的回调
    var selectedEmoticonCallBack:(emoticon: LSEmoticon ) -> ()
    
    init(selectedEmoticon:(emoticon:LSEmoticon)->()) {
        selectedEmoticonCallBack = selectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc private func clickItem(item:UIBarButtonItem) {
       
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        
        // 让 collectionView 滚动到对应位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        viewModel.loadEmotionPackages()
        setupUI()
    }

    //MARK: -界面搭建
    private func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(emotionToolBar)
        
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emotionToolBar.translatesAutoresizingMaskIntoConstraints = false
        

        let viewDict = ["vc":collectionView,"tb":emotionToolBar]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[vc]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[vc]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        
        prepareEmotionToolBar()
        prepareCollectionView()
    }
    
    private func prepareEmotionToolBar() {
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        for package in viewModel.emoticonPackages {
            items.append(UIBarButtonItem(title: package.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()

        //设置字体颜色
        emotionToolBar.tintColor = UIColor.darkGrayColor()
        
        emotionToolBar.items = items
    }
    
    private func prepareCollectionView() {
        
        //注册cell
        collectionView.registerClass(LSEmotionViewCell.self, forCellWithReuseIdentifier: LSEmotionViewCellID)
        
        //指定数据源
        collectionView.dataSource = self
        collectionView.delegate = self
    }

    //MARK: -懒加载控件
    private lazy var emotionToolBar = UIToolbar()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LSEmotionFlowLayout())

    private lazy var viewModel = LSEmotionViewModel()
}

/// 表情键盘的布局
private class LSEmotionFlowLayout:UICollectionViewFlowLayout {
    
    /// 准备布局，第一次使用的时候会被调用 － collectionView 的大小已经确定(已经完成自动布局)
    /// 准备布局方法，会在数据源(cell 的个数)前调用，可以在此准备 layout 的属性
    private override func prepareLayout() {
        super.prepareLayout()
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        let width = collectionView!.bounds.width / 7
        
        let margin = (collectionView!.bounds.height - 3 * width) * 0.5
        
        itemSize = CGSize(width: width, height: width)
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
}

//MARK: UICollectionViewDataSource
extension LSEmotionKeyboardController:UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return viewModel.emoticonPackages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return viewModel.emoticonPackages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSEmotionViewCellID, forIndexPath: indexPath) as! LSEmotionViewCell
        
        cell.emoticon = viewModel.emoticon(indexPath)
        
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        selectedEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
      
    }
    
    
}


private class LSEmotionViewCell: UICollectionViewCell {
    
    var emoticon: LSEmoticon? {
        didSet{
            
            //图片
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            //emoji
            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            
            /// 删除按钮
            if emoticon!.isRemove {
                
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
    
        emoticonButton.backgroundColor = UIColor.whiteColor()
        
        emoticonButton.frame = CGRectInset(bounds, 2, 2)
        // 设置字体
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var emoticonButton = UIButton()
}
